home *** CD-ROM | disk | FTP | other *** search
/ Pascal Super Library / Pascal Super Library (CW International)(1997).bin / LIBRARY / PAS_0493 / SETBITS.PAS < prev    next >
Pascal/Delphi Source File  |  1993-04-15  |  2KB  |  76 lines

  1. {─ Fido Pascal Conference ────────────────────────────────────────────── PASCAL ─
  2. Msg  : 348 of 353
  3. From : Sean Palmer                         1:104/123.0          13 Apr 93  15:08
  4. To   : Dane Walther
  5. Subj : Setting Bits
  6. ────────────────────────────────────────────────────────────────────────────────
  7.  DW> What if I want to just access a bit?  Say I have a byte, to store
  8.  DW> various access levels (if it does/doesn't have this, that, or the
  9.  DW> other).  How can I
  10.  
  11.  DW> 1)  Access, say, bit 4?
  12.  DW> 2)  Give, say, bit 4, a value of 1?
  13.  
  14.  DW> I have a simple routine that does "GetBit:= Value SHR 1;" to return
  15.  DW> a value, but how can I *SET* a value?  And is the above a good
  16.  DW> method? I only have TP5.5, so I can't do the ASM keyword (yet..).
  17.  
  18. OK. No feelthy 6.0 inline assembling....
  19.  
  20. You COULD use TP sets to do it...        }
  21.  
  22. type
  23.  tByte=set of 0..7;
  24. var
  25.  b:byte;
  26.  
  27. to get:
  28.  write('Bit 0 is ',boolean(0 in tByte(b)));
  29.  
  30. to set:
  31.  tByte(b):=tByte(b)+[1,3,4]-[0,2];
  32.  
  33.  
  34. {these next routines should be fairly fast...}
  35.  
  36. type
  37.  bitNum=0..7;
  38.  bit=0..1;
  39.  
  40. function getBit(b:byte;n:bitNum):bit;begin
  41.  getBit:=bit(odd(b shr n));
  42.  end;
  43.  
  44. function setBit(b:byte;n:bitNum):byte;begin
  45.  setBit:=b or (1 shl n);
  46.  end;
  47.  
  48. function clrBit(b:byte;n:bitNum):byte;begin
  49.  clrBit:=b and hi($FEFF shl n);
  50.  end;
  51.  
  52. OR.....using INLINE() code  (the fastest)
  53.  
  54. {These are untested but I'm getting fairly good at assembling by hand...8) }
  55.  
  56. function getBit(b:byte;n:bitNum):bit;inline(
  57.  $59/      {pop cx}
  58.  $58/      {pop ax}
  59.  $D2/$E8/  {shr al,cl}
  60.  $24/$01); {and al,1}
  61.  
  62. function setBit(b:byte;n:bitNum):byte;assembler;
  63. ($59/      {pop cx}
  64.  $58/      {pop ax}
  65.  $B3/$01/  {mov bl,1}
  66.  $D2/$E3/  {shl bl,cl}
  67.  $0A/$C3); {or al,bl}
  68.  end;
  69.  
  70. function clrBit(b:byte;n:bitNum):byte;assembler;
  71. ($59/      {pop cx}
  72.  $58/      {pop ax}
  73.  $B3/$FE/  {mov bl,$FE}
  74.  $D2/$C3/  {rol bl,cl}
  75.  $22/$C3); {or al,bl}
  76.  end;